package com.qq.controller;

import com.qq.entity.User;
import com.qq.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/QQ")
public class QQCodeController {

    @Autowired
    private UserService userService;

    @RequestMapping("/register")
    public String register(){
        return "register";
    }

    @PostMapping("/toRegister")
    public String toRegister(
            @ModelAttribute User user,
            @RequestParam("code") String code,
            HttpSession session) {

        // 从 session 中获取存储的验证码
        String storedCode = (String) session.getAttribute("emailCode");

        if (storedCode == null || !storedCode.equals(code)) {
            return "验证码错误";
        }

        // 校验成功后可以继续进行注册逻辑
        boolean success = saveUserToDatabase(user);
        if (!success) {
            return "注册失败，请稍后重试";
        }
        // 返回成功页面
        return "success";
    }

    private boolean saveUserToDatabase(User user) {
        boolean row = userService.save(user);
        return true;
    }
}
